package cn.itcast.work.controller.category;


import cn.itcast.work.pojo.ArticleCategory;
import cn.itcast.work.pojo.Text;
import cn.itcast.work.pojo.User;
import cn.itcast.work.service.category.CategoryService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;

/**
 * * @author: Mao Wanting
 * * @date: 2024/6/7
 * *description: 收藏夹相关操作
 **/
@Slf4j
@Controller
@RequestMapping("/CategoryController")
public class CategoryController {

    @Resource(name = "CategoryService")
    private CategoryService categoryService;


    //查询收藏夹
    @GetMapping("/selectCategory")
    @ResponseBody
    public Map<String, Object> selectCategory(HttpSession session) {
        log.info("开始查询");
        User user = (User) session.getAttribute("user");
        Map<String, Object> response = new HashMap<>();
        if (user == null) {
            response.put("result", 0);
            response.put("message", "尚未登录，无法查看收藏夹");
            log.warn("[controller]:尚未登录，无法查看收藏夹");
            return response;
        } else {
            try {
                Map<ArticleCategory, List<Text>> categories = categoryService.showCategory(user, session);
                Map<String, List<String>> jsonCategories = new HashMap<>();
                for (Map.Entry<ArticleCategory, List<Text>> entry : categories.entrySet()) {
                    ArticleCategory category = entry.getKey();
                    List<String> textsTitle = new ArrayList<>();
                    entry.getValue().forEach(text -> {
                        textsTitle.add(text.getTitle());
                    });
                    jsonCategories.put(category.getCategoryname(), textsTitle);
                }
                response.put("categories", jsonCategories);
                response.put("message", "获取收藏夹成功！");
                response.put("result", 1);
                log.info("[controller]:搜索收藏夹成功！");
                return response;
            } catch (Exception e) {
                response.put("result", 0);
                response.put("message", "出错了" + e.getMessage());
                log.error("[controller]:搜索收藏夹出错...{}", e.getMessage());
                return response;
            }
        }
    }


    /**
     * 增加收藏夹
     */
    @RequestMapping(value = "/addCategory", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object addCategory(HttpSession httpSession,
                              @RequestParam("category") String categoryName,
                              @RequestParam("introduction") String introduction) {

        User user = (User) httpSession.getAttribute("user");
        categoryService.showCategory(user, httpSession);
        Map<ArticleCategory, List<Text>> articleCategoryListMap = (Map<ArticleCategory, List<Text>>) httpSession.getAttribute("category");
        Set<ArticleCategory> set = articleCategoryListMap.keySet();//得到收藏夹集合
        Map<String, String> JsonStr = new HashMap<>();
        String result;
        for (ArticleCategory category : set) {
            if (category.getCategoryname().equals(categoryName)) {
                result = "添加失败，您已有此收藏夹，不需要在重复创建哦~";
                JsonStr.put("result", result);
                return JsonStr;
            }
        }
        //收藏夹信息
        ArticleCategory articleCategory = new ArticleCategory();
        articleCategory.setCategoryname(categoryName);
        if (!introduction.equals("")) {
            articleCategory.setIntroduction(introduction);
        }
        result = categoryService.addCategory(user, articleCategory);//添加的结果

//            Map<String,String> JsonStr=new HashMap<>();
        JsonStr.put("result", result);
        //重新刷新一遍
        categoryService.showCategory(user, httpSession);
        return JsonStr;
    }

    /**
     * 增加文章进收藏夹
     */
    @RequestMapping(value = "addArticle")
    @ResponseBody
    public Map<String, Object> addArticle(@RequestParam("category") @Value("默认收藏夹") String category,
                                          @RequestParam("text_title") String title,
                                          HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");

        user.setId(categoryService.selectUserId(user));
        httpSession.setAttribute("user", user);//得到有id的user

        ArticleCategory articleCategory = new ArticleCategory();
        articleCategory.setCategoryname(category);
        Text text = new Text();
        text.setTitle(title);
        categoryService.showCategory(user, httpSession);
        return categoryService.addArticle(user, text, articleCategory);

    }

    /**
     * 删除收藏夹
     */
    @RequestMapping(value = "/deleteCategory", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object deleteCategory(HttpSession httpSession,
                                 @RequestParam("category") String category) {

        User user = (User) httpSession.getAttribute("user");

        ArticleCategory articleCategory = new ArticleCategory();

        articleCategory.setCategoryname(category);
        String result = null;
        result = categoryService.deleteCategoryAll(user, articleCategory);
        categoryService.showCategory(user, httpSession);
        Map<String, String> JsonStr = new HashMap<>();
        JsonStr.put("result", result);
        categoryService.showCategory(user, httpSession);
        return JsonStr;

    }

    /**
     * 删除文章
     */
    @RequestMapping(value = "/deleteArticle")
    @ResponseBody
    public Object deleteArticle(HttpSession httpSession,
                                @RequestParam("category") String category,
                                @RequestParam("text_title") String title) throws IOException {

        User user = (User) httpSession.getAttribute("user");

        Text text = new Text();
        text.setTitle(title);

        ArticleCategory articleCategory = new ArticleCategory();
        articleCategory.setCategoryname(category);

        String result = null;
        result = categoryService.deleteArticle(user, articleCategory, text);

        Map<String, String> JsonStr = new HashMap<>();
        JsonStr.put("result", result);
        categoryService.showCategory(user, httpSession);
        return JsonStr;

    }

    //更改收藏夹名称
    @RequestMapping(value = "updateCategory")
    @ResponseBody
    public Object updateArticle(HttpSession httpSession,
                                @RequestParam("old") String oldCategory,
                                @RequestParam("new") String newCategory) {
        User user = (User) httpSession.getAttribute("user");

        ArticleCategory articleCategory = new ArticleCategory();
        articleCategory.setCategoryname(oldCategory);
        String result = null;

        result = categoryService.updateCategory(user, articleCategory, newCategory);
        categoryService.showCategory(user, httpSession);

        Map<String, String> JsonStr = new HashMap<>();
        JsonStr.put("result", result);
        categoryService.showCategory(user, httpSession);
        return JsonStr;
    }
}
